package com.zhuhaibaoxian.wanjiuseller.retrofit;

import android.content.Context;


import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zhuhaibaoxian.wanjiuseller.app.MyApplication;
import com.zhuhaibaoxian.wanjiuseller.utils.Constants;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by Administrator on 2018/1/13.
 *
 */

public class Api {
    private static Api api;
    private static String url = Constants.BASE1;
    private static String CACHE_CONTROL = "CACHE_CONTROL";
    private Converter.Factory factory = GsonConverterFactory.create();
    private IService iService;
    private static volatile Retrofit retrofit;

    public IService getiService() {
        return iService;
    }

    //私有实例化时就创建retrofit对象（无参）
    private Api(){
        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(factory).client(client()).build();
        iService = retrofit.create(IService.class);
    }

    //私有实例化时就创建retrofit对象（有参）
    private Api(String url){
        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(factory).client(client()).build();
        iService = retrofit.create(IService.class);
    }

    private static OkHttpClient client(){
//        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor("cache");
//        interceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        int cacheSize = 200 * 1024 * 1024;
        File cacheDirectory = new File(MyApplication.context.getCacheDir(), "httpcache");
        Cache cache = new Cache(cacheDirectory, cacheSize);
//        builder.addInterceptor(interceptor);
        builder.addInterceptor((Interceptor) new HeaderInterceptor());
//        builder.addNetworkInterceptor(new CacheForceInterceptorNoNet());

//        builder.addInterceptor(new CacheForceInterceptorNoNet());
//        builder.addNetworkInterceptor(new CacheInterceptorOnNet());

        builder.readTimeout(8, TimeUnit.SECONDS);
        builder.connectTimeout(8, TimeUnit.SECONDS);
        OkHttpClient client = builder.cache(cache).build();

        return client;
    }

    public static Api getInstance(){
        if (api==null) {
            api = new Api();
        }
        return api;
    }

    public static Api getInstance(String url){
        if (api==null) {
            api = new Api(url);
        }
        return api;
    }

    public static IService singletonGank (Context context){
        if (retrofit == null) {
            synchronized (Api.class){
                if (retrofit == null) {
                    retrofit=new Retrofit.Builder().baseUrl(url)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).client(client()).build();
//                    retrofit=new Retrofit.Builder().baseUrl(url)
//                            .addConverterFactory(GsonConverterFactory.create())
//                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                            //偷个懒直接写一起
//                            .client(new OkHttpClient.Builder()
//                                    .cookieJar(new NovateCookieManger(context))
//                                    .cache(new Cache(new File(context.getExternalCacheDir(),"test_cache"),10 * 1024 * 1024))
//                                    .addInterceptor(new CaheInterceptor(context))
//                                    .addNetworkInterceptor(new CaheInterceptor(context))
//                                    .connectTimeout(5, TimeUnit.SECONDS)
//                                    .build())
//                            .build();
                }
            }
        }
        return retrofit.create(IService.class);
    }

    /**
     * 头拦截器
     */
    private static class HeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String token = "";
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    .header("Authorization", token)
                    .method(original.method(),original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    }

}
